﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SPHelpers.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   Defines the SPHelpers type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Collaboris.DataAccess.SharePoint
{
    using System;

    using Microsoft.SharePoint;

    /// <summary>
    /// The sp helpers.
    /// </summary>
    public class SPHelpers
    {
        #region Public Methods

        /// <summary>
        /// Checks whether the specified login name belongs to a valid user of the Web site,
        /// and if the login name does not already exist, adds it to the Web site. 
        /// </summary>
        /// <param name="webId">
        /// The id of the web that we want to make the user a member of
        /// </param>
        /// <returns>
        /// </returns>
        public static SPUser EnsureUser(SPWeb web, string username)
        {
            SPUser user = null;

            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                    {
                        using (var site = new SPSite(web.Site.ID))
                        {
                            using (SPWeb elevatedWeb = site.OpenWeb(web.ID))
                            {
                                user = elevatedWeb.EnsureUser(username);
                            }
                        }
                    });

            return user;
        }

        #endregion
    }
}